<template>
  <n-card
    title="📖 阶段完成情况"
    embedded
    bordered
  >
    <StageYearDuration :events="events"></StageYearDuration>
  </n-card>

  <n-divider></n-divider>

  <n-card
    title="📖 统计情况"
    embedded
    bordered
  >
    <n-space vertical>
      <IdMultilSelect v-model="choose"></IdMultilSelect>
      <n-radio-group
        v-model:value="value"
        name="radiobuttongroup1"
        :disabled="!choose.toEdit"
      >
        <n-space>
          <n-radio
            v-for="song in songs"
            :key="song.value"
            :value="song.value"
          >
            {{ song.label }}
          </n-radio>
          <n-button
            type="primary"
            size="tiny"
            dashed
            @click="moveTimeStamp(-1)"
          >
            上一{{ value }}
          </n-button>
          <n-button
            type="primary"
            size="tiny"
            dashed
            @click="moveTimeStamp(1)"
          >
            下一{{ value }}
          </n-button>
        </n-space>
      </n-radio-group>
    </n-space>
    <IdTimeBar
      :data="barData"
      :key="key"
    ></IdTimeBar>
    <TimePie
      :data="timePieData"
      :type="2"
      :key="key + 15"
    ></TimePie>
  </n-card>
</template>

<script lang="ts" setup>
import TimePie from "@/components/common/TimePie.vue";
import IdMultilSelect from "@/components/common/idMultilSelect.vue";
import IdTimeBar from "@/components/stat/charts/IdTimeBar.vue";
import StageYearDuration from "@/components/stat/charts/StageYearDuration.vue";
import { TaskLogData } from "@model/TaskLogMap";
import { StageList } from "@model/stage";
import UseCacheIdStatMap from "@pinias/UseCacheIdStatMap";
import UseFieldTree from "@pinias/UseFieldTree";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import pinia from "@pinias/pinia";
import { beforeDDL, timestampToDateTime } from "@utils/DateUtils";
import { onMounted, reactive, ref, watch } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting = getSurfaceSetting();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();
const { getCacheIdStatMap } = UseCacheIdStatMap(pinia);
const cacheIdStatMap = getCacheIdStatMap();

//当前页面数据
// 阶段日历
const key = ref(0);
const events = new Array<{ title: string; start: string; end: string; color: string; description: string }>();
stageList.stageData.map(value1 => {
  for (const stageDatum of value1.startTime) {
    events.push({
      title: value1.name,
      start: timestampToDateTime(stageDatum.start),
      end: timestampToDateTime(stageDatum.end),
      color: value1.finished ? "gray" : "red",
      description: "",
    });
  }
});

// 柱状图 饼图
const value = ref(surfaceSetting.statChooseTimeRange);
const songs = ["周", "月", "年"].map(s => {
  return { value: s, label: s };
});
const choose = reactive<{
  chooseTaskResults: Array<number>;
  chooseLifeResults: Array<number>;
  hasFinish: boolean;
  toEdit: boolean;
  multiple: boolean;
  cascade: boolean;
  timeStamp: number;
}>({
  chooseTaskResults: [...surfaceSetting.statChooseTaskResults],
  chooseLifeResults: [...surfaceSetting.statChooseLifeResults],
  hasFinish: true,
  toEdit: false,
  multiple: true,
  cascade: false,
  timeStamp: new Date().getTime(),
});
const moveTimeStamp = (type: number) => {
  if (value.value === "周") {
    choose.timeStamp = beforeDDL(choose.timeStamp, type * 7, 1);
  }
  if (value.value === "月") {
    choose.timeStamp = beforeDDL(choose.timeStamp, type, 2);
  }
  if (value.value === "年") {
    choose.timeStamp = beforeDDL(choose.timeStamp, type, 3);
  }
};
const barData = ref<{
  timeRange: Array<string>;
  series: Array<{ id: number; name: string; takeTimeList: Array<number> }>;
}>({
  timeRange: new Array<string>(),
  series: new Array<{ id: number; name: string; takeTimeList: Array<number> }>(),
});
const timePieData = ref(new Array<{ value: number; name: string | undefined }>());

const getBarData = async () => {
  let chooseIds = new Array<number>();
  if (surfaceSetting.statChooseLifeResults.length + surfaceSetting.statChooseTaskResults.length === 0) {
    chooseIds = [...fieldTree.fieldData.map(value1 => value1.id)];
    surfaceSetting.statChooseTaskResults = [...chooseIds];
  } else chooseIds = [...surfaceSetting.statChooseLifeResults, ...surfaceSetting.statChooseTaskResults];
  const id2NameMap = new Map<number, string>();
  for (const chooseId of surfaceSetting.statChooseLifeResults) {
    const father = await TaskLogData.getFatherId(2, chooseId);
    console.log("++++++++++++++++", father, chooseId);
    if (father.length > 0 && father[0].name !== undefined) id2NameMap.set(chooseId, father[0].name);
  }
  for (const chooseId of surfaceSetting.statChooseTaskResults) {
    const father = await TaskLogData.getFatherId(1, chooseId);
    // console.log("++++++++++++++++", father,chooseId);
    if (father.length > 0 && father[0].name !== undefined) id2NameMap.set(chooseId, father[0].name);
  }
  const result = await cacheIdStatMap.getTakeTime4Stat(chooseIds, choose.timeStamp, surfaceSetting.statChooseTimeRange);
  for (const resultElement of result.series) {
    const id = resultElement.id;
    const name = id2NameMap.get(id);
    resultElement.name = name === undefined ? "" : name;
  }
  timePieData.value = result.series.map(value1 => {
    let times = 0;
    value1.takeTimeList.forEach(v => (times += v));
    return { name: value1.name, value: times };
  });
  // console.log("++++++++++++++++", result, surfaceSetting.statChooseTaskResults);
  barData.value = result;
};
onMounted(async () => {
  await getBarData();
});
watch(choose, async () => {
  if (!choose.toEdit) {
    surfaceSetting.statChooseLifeResults = [...choose.chooseLifeResults];
    surfaceSetting.statChooseTaskResults = [...choose.chooseTaskResults];
    surfaceSetting.statChooseTimeRange = value.value;
    //
    await getBarData();
    key.value = new Date().valueOf();
  }
});
</script>
